<template>
  <div class="questionsNewContainer">
    <p>李嘉亮</p>

    <el-card class="box-card">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="学科" prop="subjectID">
          <el-select
            @change="onChangeSimple"
            v-model="ruleForm.subjectID"
            placeholder="请选择"
          >
            <el-option
              v-for="item in options.simple"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录" prop="catalogID">
          <el-select v-model="ruleForm.catalogID" placeholder="请选择">
            <el-option
              v-for="item in options.directorys"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业" prop="enterpriseID">
          <el-select v-model="ruleForm.enterpriseID" placeholder="请选择">
            <el-option
              v-for="item in options.enterprise"
              :key="item.id"
              :label="item.shortName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="city" label="城市" prop="province">
          <el-select
            @change="onChangeProvinces"
            v-model="ruleForm.province"
            placeholder="请选择"
          >
            <el-option
              v-for="item in options.provinces"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
          <el-select v-model="ruleForm.city" placeholder="请选择">
            <el-option
              v-for="item in options.citys"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向" prop="direction">
          <el-select v-model="ruleForm.direction" placeholder="请选择">
            <el-option
              v-for="item in options.direction"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型">
          <el-radio-group
            @change="onChangeRadio"
            v-model="ruleForm.questionType"
          >
            <el-radio label="1">单选</el-radio>
            <el-radio label="2">多选</el-radio>
            <el-radio label="3">简答</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度">
          <el-radio-group v-model="ruleForm.difficulty">
            <el-radio label="1">简单</el-radio>
            <el-radio label="2">一般</el-radio>
            <el-radio label="3">困难</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 富文本 -->
        <el-form-item label="题干" prop="question">
          <quill-editor
            v-model="ruleForm.question"
            ref="myQuillEditor"
            :options="editorOption"
          ></quill-editor
        ></el-form-item>
        <!-- 选项 -->
        <el-form-item v-if="isShowRadio" label="选项">
          <el-radio-group v-model="radioCurrent" class="options">
            <div
              class="selectionBox"
              v-for="(item, index) in ruleForm.options"
              :key="item.code"
            >
              <el-checkbox v-if="isCheckbox" v-model="item.isRight">{{
                item.code
              }}</el-checkbox>
              <el-radio
                @change="radioChange(index)"
                v-else
                :label="item.isRight"
                >{{ item.code }}</el-radio
              >
              <el-input v-model="item.title"></el-input>
              <Upload :imgurl="item" class="uploadImg" @imgURL="item.img = $event"></Upload>
            </div>
          </el-radio-group>
          <el-button
            @click="addCheckbox"
            :disabled="!isCheckbox"
            type="danger"
            size="mini"
            >+新增选项与答案</el-button
          >
        </el-form-item>
        <el-form-item label="解析视频">
          <el-input v-model="ruleForm.videoURL"></el-input>
        </el-form-item>
        <!-- 富文本 -->
        <el-form-item label="答案解析" prop="answer">
          <quill-editor
            v-model="ruleForm.answer"
            ref="myQuillEditor"
            :options="editorOption"
          ></quill-editor
        ></el-form-item>
        <!-- 题目备注 -->
        <el-form-item label="题目备注" prop="remarks">
          <el-input
            type="textarea"
            rows="4"
            v-model="ruleForm.remarks"
          ></el-input>
        </el-form-item>
        <!-- 标签 -->
        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="ruleForm.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择文章标签"
          >
            <el-option
              v-for="item in options.tags"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSave">确认提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { sortBy } from '@/filters'
import Upload from '@/components/UploadImage'
import hljs from 'highlight.js'
import 'highlight.js/styles/xcode.css'
import { simple } from '@/api/hmmm/subjects'
import { simple as dirSimple } from '@/api/hmmm/directorys'
import { provinces, citys } from '@/api/hmmm/citys'
import { direction } from '@/api/hmmm/constants'
import { list } from '@/api/hmmm/companys'
import { simple as tagsSimple } from '@/api/hmmm/tags'
import { add, detail, update } from '@/api/hmmm/questions'
export default {
  name: 'QiestionsNew',
  data () {
    return {
      // 循环的数据
      options: {
        provinces: provinces(),
        citys: [],
        direction,
        enterprise: [], // 企业
        simple: [], // 学科
        directorys: [], // 目录
        tags: [] // 标签
      },

      // 绑定的数据
      ruleForm: {
        subjectID: '', // 学科
        catalogID: '', // 当前目录
        enterpriseID: '', // 企业
        city: '', // 城市 1
        province: '', // 城市 1
        direction: '', // 方向 1
        questionType: '1', // 题型
        difficulty: '1', // 难度 1
        question: '', // 题干
        videoURL: '', // 视频
        answer: '', // 答案 1
        remarks: '', // 备注
        tags: '', // 当前选择的标签
        options: [
          {
            code: 'A',
            isRight: 0,
            title: '',
            img: ''
          },
          {
            code: 'B',
            isRight: 0,
            title: '',
            img: ''
          },
          {
            code: 'C',
            isRight: 0,
            title: '',
            img: ''
          },
          {
            code: 'D',
            isRight: 0,
            title: '',
            img: ''
          }
        ]
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: ['blur', 'change'] }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: ['blur', 'change'] }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: ['blur', 'change'] }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: ['blur', 'change'] }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: ['blur', 'change'] }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: ['blur', 'change'] }
        ],
        answer: [
          { required: true, message: '请输入答案', trigger: ['blur', 'change'] }
        ],
        remarks: [
          { required: true, message: '请输入备注', trigger: ['blur', 'change'] }
        ],
        tags: [
          { required: true, message: '请选择标签', trigger: ['blur', 'change'] }
        ]
      },
      // 富文本
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // toggled buttons
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote', 'code-block'],
            ['image', 'link']
          ],
          // 代码块高亮
          syntax: {
            highlight: text => {
              return hljs.highlightAuto(text).value // 这里就是代码高亮需要配置的地方
            }
          }
        }
      },

      isCheckbox: false, // 是否为复选框
      isShowRadio: true, // 是否显示选择框
      checkNum: 68,
      radioCurrent: 1
    }
  },
  created () {
    this.loadQuestionsInfo()
  },
  components: {
    Upload
  },

  methods: {
    async loadQuestionsInfo () {
      if (this.$route.query.id) {
        this.loadInfo()
      }
      try {
        const { data: res } = await list({ pagesize: 100000 })
        this.options.enterprise = res.items
        const { data: resSimple } = await simple()
        this.options.simple = resSimple
      } catch (err) {
        console.dir(err)
      }
    },
    // 如果是点击修改跳转进来的就发起这个请求
    async loadInfo () {
      try {
        const { data: infoRes } = await detail({ id: this.$route.query.id })
        await this.onChangeSimple(infoRes.subjectID)
        // 判断题型
        if (infoRes.questionType === '1') {
          this.isCheckbox = false
        } else if (infoRes.questionType === '2') {
          this.isCheckbox = true
          infoRes.options.forEach(item => {
            item.isRight = !!item.isRight
          })
        } else {
          this.isShowRadio = false
        }
        infoRes.options.sort(sortBy('id'))
        if (infoRes.tags) {
          infoRes.tags = infoRes.tags.split(',')
        }
        this.ruleForm = infoRes
      } catch (err) {
        console.log(err)
      }
    },
    onChangeProvinces (val) {
      this.options.citys = citys(val)
      this.ruleForm.city = this.options.citys[0]
    },
    async onChangeSimple (subjectID) {
      try {
        this.ruleForm.catalogID = ''
        const { data: res } = await dirSimple({ subjectID })
        this.options.directorys = res
        const { data: tagsRes } = await tagsSimple({ subjectID })
        this.options.tags = tagsRes
      } catch (err) {
        console.log(err)
      }
    },
    // 添加多选
    addCheckbox () {
      this.checkNum++
      if (this.checkNum === 127) {
        this.checkNum = 128
      }
      const val = String.fromCharCode(this.checkNum)
      this.ruleForm.options.push({
        code: val,
        isRight: 0,
        title: '',
        img: ''
      })
    },
    // 点击单选多选
    onChangeRadio (val) {
      if (val === '1') {
        this.isCheckbox = false
        this.isShowRadio = true
        this.ruleForm.options.splice(4)
        this.ruleForm.options.forEach(item => {
          item.isRight = 0
        })
      } else if (val === '2') {
        this.isCheckbox = true
        this.isShowRadio = true
        this.ruleForm.options.forEach(item => {
          item.isRight = false
        })
      } else {
        this.isShowRadio = false
      }
    },
    // 单选框组
    radioChange (i) {
      this.ruleForm.options.forEach(item => {
        item.isRight = 0
        this.ruleForm.options[i].isRight = 1
        this.radioCurrent = 1
      })
    },
    async onSave () {
      try {
        await this.$refs.ruleForm.validate()
        this.ruleForm.tags = this.ruleForm.tags.join(',')
        if (this.$route.query.id) {
          await update(this.ruleForm)
        } else {
          await add(this.ruleForm)
        }
        this.$message.success('添加成功！')
        this.$router.push('/questions/list')
      } catch (err) {
        console.dir(err)
      }
    }
  }
}
</script>

<style scoped lang="less">
.questionsNewContainer {
  padding: 10px;
  // 富文本
  /deep/ .ql-toolbar.ql-snow {
    padding: 0;
  }
  /deep/ .ql-container {
    height: 200px;
  }
  /deep/ .options {
    display: flex;
    flex-direction: column;
    width: 430px;
  }
  /deep/ .el-select {
    width: 400px;
  }
  .city {
    .el-select {
      width: 200px;
    }
  }
  .selectionBox {
    position: relative;
    display: flex;
    align-items: center;
    margin-bottom: 35px;
    .el-checkbox:last-of-type {
      margin-right: 30px;
    }
    .el-input {
      width: 240px;
    }
  }
  .uploadImg {
    position: absolute;
    right: 15px;
  }
}
</style>
